import { BLEProtocol } from '../../utils/bleProtocol';

interface Device {
  deviceId: string;
  name: string;
}

interface Service {
  uuid: string;
  isPrimary: boolean;
}

interface Characteristic {
  uuid: string;
  properties: {
    read: boolean;
    write: boolean;
    notify: boolean;
    indicate: boolean;
    writeWithoutResponse?: boolean; // 改为可选属性
  };
}

Page({
  data: {
    isScanning: false,
    devices: [] as Device[],
    connectedDevice: null as Device | null,
    status: '',
    lockStatus: false,
    bleButtonLabels: ['按键1', '按键2', '按键3', '按键4', '按键5', '按键6'],

    _foundDevices: new Set<string>(),
    readServiceUuid: '',
    readCharUuid: '',
    writeServiceUuid: '',
    writeCharUuid: '',
    servicesInfo: [] as {
      uuid: string;
      originalUuid: string;
      isPrimary: boolean;
      characteristics: {
        uuid: string;
        properties: {
          read: boolean;
          write: boolean;
          notify: boolean;
          indicate: boolean;
        };
      }[];
    }[],
    deviceData: '',
    currentSpeed: 0,
    batteryLevel: 0,
    totalMileage: 0,
    filterName: '',
    notifyServiceUuid: '',
    notifyCharUuid: '',
    retryCount: 0
  },

  // 切换扫描状态
  // 根据当前扫描状态，开始或停止蓝牙设备扫描
  toggleScan() {
    if (this.data.isScanning) {
      this.stopScan();
    } else {
      this.startScan();
    }
  },
  // 通用按键长按处理
  handleButtonLongPress(e: { currentTarget: { dataset: { buttonNumber: number } } }) {
    const buttonNumber = e.currentTarget.dataset.buttonNumber;
    const settingsKey = `bleButton${buttonNumber}_Settings`;
    const title = `按键设置`;
    const defaultLabel =  `bleButton${buttonNumber}_Settings`;
    const settings = wx.getStorageSync(settingsKey) || defaultLabel;
      wx.showModal({
        title,
        editable: true,
        content: `按键标签:${settings.label}\n发送内容:${settings.data}`,
        editableContent: {
          editableLines: [0, 1],
          editableRanges: [
            {line: 0, start: 5, end: 20},
            {line: 1, start: 5, end: 20}
          ]
        },
        success: (res) => {
          if (res.confirm) {
            const settings = res.content.split('\n');
            if (settings.length === 2) {
              const buttonLabel = settings[0].split(':')[1] || defaultLabel;
              const hexData = settings[1].split(':')[1] || '01020304';
              wx.setStorageSync(settingsKey, {
                label: buttonLabel,
                data: hexData
              });
              this.setData({
                [`bleButtonLabels[${buttonNumber - 1}]`]: buttonLabel,
                [`bleButton${buttonNumber}_CommandData`]: hexData
              });
            }
          }
        }
      });
    },

  // 停止扫描
  // 调用微信小程序API停止蓝牙设备扫描，并更新扫描状态
  stopScan() {
    wx.stopBluetoothDevicesDiscovery({
      success: () => {
        this.setData({ isScanning: false });
        wx.showToast({ title: '已停止扫描' });
      }
    });
  },

  // 开始扫描
  // 调用微信小程序API启动蓝牙设备扫描，并初始化设备列表
  startScan() {
    // 检查并加载UUID设置
    const storedUuids = wx.getStorageSync('bleUuids') || {};
    if (!this.data.readServiceUuid || !this.data.readCharUuid || 
        !this.data.writeServiceUuid || !this.data.writeCharUuid) {
      this.setData({
        readServiceUuid: storedUuids.readServiceUuid || 'FFE0',
        readCharUuid: storedUuids.readCharUuid || 'FFE4',
        writeServiceUuid: storedUuids.writeServiceUuid || 'FFE5',
        writeCharUuid: storedUuids.writeCharUuid || 'FFE9'
      });
    }

    wx.openBluetoothAdapter({
      success: () => {
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false,
          success: () => {
            this.setData({
              isScanning: true,
              devices: [],
              _foundDevices: new Set()
            });
            wx.onBluetoothDeviceFound(this.handleDeviceFound.bind(this));
          }
        });
      }
    });
  },

  // 打开过滤弹窗
  // 显示模态对话框，允许用户输入设备名称进行过滤
  openFilterDialog() {
    wx.showModal({
      title: '广播过滤',
      editable: true,
      placeholderText: '请输入过滤名称',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            filterName: res.content
          });
        }
      }
    });
  },

  openUuidDialog() {
    // 读取存储的 UUID
    const storedUuids = wx.getStorageSync('bleUuids') || {};
    wx.showModal({
      title: 'UUID设置',
      editable: true,
      content: `读服务UUID:${storedUuids.readServiceUuid || 'FFE0'}
读特征UUID:${storedUuids.readCharUuid || 'FFE4'}
写服务UUID:${getShortUuid(storedUuids.writeServiceUuid) || 'FFE5'}
写特征UUID:${getShortUuid(storedUuids.writeCharUuid) || 'FFE9'}`,
      placeholderText: '请输入16bit UUID(如FFE0)',
      editableContent: {
        editableLines: [1, 2, 3],
        editableRanges: [
          {line: 0, start: 7, end: 11},
          {line: 1, start: 7, end: 11},
          {line: 2, start: 7, end: 11},
          {line: 3, start: 7, end: 11}
        ]
      },
      success: (res) => {
        if (res.confirm) {
          const uuids = res.content.split('\n');
          if (uuids.length === 4) {
            const uuidRegex = /^[0-9A-Fa-f]{4}$/;
            const isValid = uuids.every(uuid => uuidRegex.test(uuid.split(':')[1]));
            if (!isValid) {
              wx.showToast({ title: '输入的16bit UUID格式不正确', icon: 'none' });
              return;
            }
            const newUuids = {
              readServiceUuid: uuids[0].split(':')[1] || 'FFE0',
              readCharUuid: uuids[1].split(':')[1] || 'FFE4',
              writeServiceUuid: uuids[2].split(':')[1] || 'FFE5',
              writeCharUuid: uuids[3].split(':')[1] || 'FFE9'
            };
            this.setData(newUuids);
            // 存储新的 UUID
            wx.setStorageSync('bleUuids', newUuids);
          }
        }
      }
    });
  },

  // 处理发现的蓝牙设备
  // 处理蓝牙设备发现事件，根据过滤条件更新设备列表
  handleDeviceFound(res: { devices: Device[] }) {
    const devices = res.devices || [];
    const { filterName } = this.data;
    const newFilterName = filterName ? filterName.toLowerCase() : '';
    const newDevices = devices.filter((device) =>
      !this.data._foundDevices.has(device.deviceId) &&
      device.name && device.name.trim() !== '' &&
      (newFilterName === '' || device.name.toLowerCase().includes(newFilterName))
    );

    if (newDevices.length > 0) {
      const updatedSet = new Set(this.data._foundDevices);
      newDevices.forEach((device) => updatedSet.add(device.deviceId));
      this.setData({
        devices: [...this.data.devices, ...newDevices],
        _foundDevices: updatedSet
      });
    }
  },

  // 连接蓝牙设备
  // 连接指定的蓝牙设备，并初始化相关服务
  connectDevice(deviceInfo: string | { currentTarget?: { dataset?: { deviceid?: string; device?: { deviceId: string; }; }; }; deviceId?: string; }) {
    const deviceId = this.getDeviceId(deviceInfo);
    if (!deviceId) return;

    const device = this.data.devices.find(d => d.deviceId === deviceId);
    if (!device) return;

    wx.createBLEConnection({
      deviceId,
      success: () => {
        this.setData({
          connectedDevice: device,
          status: '',
          devices: [device]
        });
        this.stopScan();
        this.initializeBLEServices().then(success => {
          if (success) {
            this.enableNotifications();
          }
        });
      },
      fail: (err) => {
        console.error('连接失败:', err);
        wx.showToast({
          title: '连接失败',
          icon: 'none'
        });
        this.setData({
          status: ''
        });
      }
    });
  },

  // 获取设备 ID
  // 从不同格式的设备信息中提取设备ID
  getDeviceId(deviceInfo: string | { currentTarget?: { dataset?: { deviceid?: string; device?: { deviceId: string; }; }; }; deviceId?: string; }): string {
    if (typeof deviceInfo === 'string') {
      return deviceInfo;
    } else if (typeof deviceInfo === 'object') {
      if (deviceInfo.currentTarget?.dataset?.deviceid) {
        return deviceInfo.currentTarget.dataset.deviceid;
      } else if (deviceInfo.currentTarget?.dataset?.device) {
        return deviceInfo.currentTarget.dataset.device.deviceId;
      } else if (deviceInfo.deviceId) {
        return deviceInfo.deviceId;
      }
    }
    return '';
  },

  // 统一获取并缓存所有服务信息
  // 获取蓝牙设备的所有服务信息，并缓存通知和写入服务
  cacheServices() {
    return new Promise<{ notifyService: Service; writeService: Service }>((resolve, reject) => {
      const connectedDevice = this.data.connectedDevice;
      if (!connectedDevice) {
        reject(new Error('未连接设备'));
        return;
      }

      wx.getBLEDeviceServices({
        deviceId: connectedDevice.deviceId,
        success: async (servicesRes) => {
          const servicesInfo = [];

          for (const service of servicesRes.services) {
            const shortUuid = getShortUuid(service.uuid);
            const characteristics = await this.getCharacteristics(service.uuid);

            servicesInfo.push({
              uuid: shortUuid,
              originalUuid: service.uuid,
              isPrimary: service.isPrimary,
              characteristics: characteristics.map(c => ({
                uuid: getShortUuid(c.uuid),
                properties: c.properties
              }))
            });
          }

          this.setData({
            servicesInfo,
            allServicesUuids: servicesInfo.map(s =>
              `服务: ${s.uuid}\n` +
              `特征值:\n${s.characteristics.map(c =>
                `  ${c.uuid} (${this.getPropertiesString(c.properties)})`
              ).join('\n')}`
            ).join('\n\n')
          });

          const readServiceUuid = this.data.readServiceUuid || 'FFE0';
          const writeServiceUuid = this.data.writeServiceUuid || 'FFE5';
          const isSameService = readServiceUuid === writeServiceUuid;
          
          const notifyService = servicesRes.services.find(s =>
            s.uuid === getFullUuid(readServiceUuid));
          const writeService = isSameService ? notifyService : servicesRes.services.find(s =>
            s.uuid === getFullUuid(writeServiceUuid));

          if (!notifyService) {
            console.error('缺少通知服务:', {
              notifyService: '未找到',
              writeService: writeService ? '找到' : '未找到'
            });
            reject(new Error('缺少通知服务'));
            return;
          }
          
          if (!isSameService && !writeService) {
            console.error('缺少写入服务:', {
              notifyService: '找到',
              writeService: '未找到'
            });
            reject(new Error('缺少写入服务'));
            return;
          }

          this.setData({
            notifyServiceUuid: notifyService.uuid,
            writeServiceUuid: isSameService ? notifyService.uuid : writeService?.uuid
          });

          resolve({
            notifyService,
// 为了避免将 undefined 赋值给 Service 类型，添加空值检查。
// 如果 writeService 为 undefined，则抛出错误，确保类型安全。
writeService: isSameService ? notifyService! : (writeService! || (() => { throw new Error('写入服务未找到'); })())
          });
        },
        fail: (err) => {
          console.error('获取服务失败:', err);
          reject(err);
        }
      });
    });
  },

  // 新增方法：获取服务的特征值
  // 获取指定服务的所有特征值信息
  getCharacteristics(serviceId: string) {
    return new Promise<Characteristic[]>((resolve) => {
      const connectedDevice = this.data.connectedDevice;
      if (!connectedDevice) {
        resolve([]);
        return;
      }

      wx.getBLEDeviceCharacteristics({
        deviceId: connectedDevice.deviceId,
        serviceId,
        success: (res) => {
          const characteristics = res.characteristics.map(c => ({
            uuid: c.uuid,
            properties: {
              read: c.properties.read,
              write: c.properties.write,
              notify: c.properties.notify,
              indicate: c.properties.indicate,
              writeWithoutResponse: 'writeWithoutResponse' in c.properties 
                ? (c.properties as any).writeWithoutResponse 
                : false // 安全访问属性
            }
          }));
          resolve(characteristics);
        },
        fail: () => resolve([])
      });
    });
  },

  // 新增方法：格式化特征值属性
  // 将特征值的属性格式化为可读字符串
  getPropertiesString(properties: { read: boolean; write: boolean; notify: boolean; indicate: boolean }) {
    const props = [];
    if (properties.read) props.push('读');
    if (properties.write) props.push('写');
    if (properties.notify) props.push('通知');
    if (properties.indicate) props.push('指示');
    return props.join(',');
  },

  // 查找并缓存特征值
  // 查找并缓存通知和写入特征值，支持重试机制
  cacheCharacteristics() {
    return new Promise<[Characteristic, Characteristic]>((resolve, reject) => {
      const connectedDevice = this.data.connectedDevice;
      if (!connectedDevice) {
        reject(new Error('未连接设备'));
        return;
      }

      if (!this.data.notifyServiceUuid || !this.data.writeServiceUuid) {
        reject(new Error('服务未初始化'));
        return;
      }

      console.log('开始获取特征值...', {
        notifyServiceUuid: this.data.notifyServiceUuid,
        writeServiceUuid: this.data.writeServiceUuid
      });
      
      Promise.all([
        new Promise<Characteristic>((resolveNotify, rejectNotify) => {
          wx.getBLEDeviceCharacteristics({
            deviceId: this.data.connectedDevice?.deviceId || '', 
            serviceId: this.data.notifyServiceUuid,
            success: (charsRes) => {
              console.log('获取到的通知服务特征值:', charsRes.characteristics);
              const notifyChar = charsRes.characteristics.find(c =>
                c.uuid === getFullUuid(this.data.readCharUuid || 'FFE4') && c.properties.notify);

              if (!notifyChar) {
                console.error('未找到通知特性');
                rejectNotify(new Error('未找到通知特性'));
                return;
              }

              this.setData({ notifyCharUuid: notifyChar.uuid });
              resolveNotify(notifyChar);
            },
            fail: (err) => {
              console.error('获取通知特征值失败:', err);
              rejectNotify(err);
            }
          });
        }),
        new Promise<Characteristic>((resolveWrite, rejectWrite) => {
          wx.getBLEDeviceCharacteristics({
            deviceId: this.data.connectedDevice?.deviceId || '', 
            serviceId: this.data.writeServiceUuid,
            success: (charsRes) => {
              console.log('获取到的写入服务特征值:', charsRes.characteristics);
              const writeChar = charsRes.characteristics.find(c => {
                const hasWrite = (c.properties as any).write || (c.properties as any).writeWithoutResponse;
                return (c.uuid === getFullUuid(this.data.writeCharUuid || 'FFE9')) &&
                  hasWrite;
              }) || charsRes.characteristics.find(c => {
                return (c.uuid === getFullUuid(this.data.writeCharUuid || 'FFE9')) &&
                  (c.properties as any).writeWithoutResponse;
              }) || charsRes.characteristics.find(c => {
                return (c.properties as any).writeWithoutResponse;
              });

              if (!writeChar) {
                const allChars = charsRes.characteristics.map(c => ({
                  uuid: c.uuid,
                  shortUuid: getShortUuid(c.uuid),
                  properties: c.properties,
                  hasWrite: (c.properties as any).write || (c.properties as any).writeWithoutResponse
                }));

                console.error('未找到写入特性', {
                  serviceId: this.data.writeServiceUuid,
                  allCharacteristics: allChars,
                  serviceUuids: {
                    notifyService: this.data.notifyServiceUuid,
                    writeService: this.data.writeServiceUuid
                  }
                });

                if (this.data.retryCount < 3) {
                  this.setData({ retryCount: this.data.retryCount + 1 });
                  console.log(`未找到写入特性，第${this.data.retryCount}次重试...`);
                  setTimeout(() => {
                    wx.getBLEDeviceCharacteristics({
                      deviceId: this.data.connectedDevice?.deviceId || '', 
                      serviceId: this.data.writeServiceUuid,
                      success: (retryRes) => {
                        const retryChar = retryRes.characteristics.find(c => {
                          const shortUuid = getShortUuid(c.uuid);
                          const hasWrite = (c.properties as any).write || (c.properties as any).writeWithoutResponse;
                          return (shortUuid === 'FFE9' || c.uuid.toUpperCase().includes('FFE9')) &&
                            hasWrite;
                        });
                        if (retryChar) {
                          this.setData({ writeCharUuid: retryChar.uuid });
                          resolveWrite(retryChar);
                        } else {
                          // if (process.env.NODE_ENV === 'development') {
                          //   console.log('未找到写入特性(FFE9)3');
                          // }
                          if (this.data.retryCount >= 3) {
                            rejectWrite(new Error(`未找到写入特性(FFE9)4`));
                          } else {
                            rejectWrite(new Error(''));
                          }
                        }
                      },
                      fail: (err) => {
                        console.error('重试获取写入特征值失败:', err);
                        rejectWrite(err);
                      }
                    });
                  }, 500);
                  return;
                }

                // if (process.env.NODE_ENV === 'development') {
                //   console.log('未找到写入特性(FFE9)8');
                // }
                rejectWrite(new Error(''));
                return;
              }

              this.setData({ writeCharUuid: writeChar.uuid });
              //console.log('成功找到写入特性:', writeChar.uuid);
              resolveWrite(writeChar);
            },
            fail: (err) => {
              console.error('获取写入特征值失败:', err);
              rejectWrite(err);
            }
          });
        })
      ]).then(resolve).catch(reject);
    });
  },

  // 初始化蓝牙服务
  // 初始化蓝牙服务，包括获取服务和特征值
  async initializeBLEServices() {
    try {
      console.log('开始初始化蓝牙服务...');
      const services = await this.cacheServices();
      console.log('获取到的服务信息:', services);

      await this.cacheCharacteristics();
      console.log('获取到的特征值信息:', {
        notifyCharUuid: this.data.notifyCharUuid,
        writeCharUuid: this.data.writeCharUuid
      });

      if (!this.data.writeCharUuid) {
        throw new Error('未找到写入特性');
      }

      console.log('蓝牙服务初始化完成');
      return true;
    } catch (err) {
      console.error('初始化蓝牙服务失败:', err);
      wx.showToast({
// 通过类型断言将 err 转换为 Error 类型
title: `初始化失败: ${(err as Error).message}`,
        icon: 'none'
      });
      return false;
    }
  },

  // 启用通知特性
  // 启用蓝牙设备的通知特性，用于接收设备数据
  enableNotifications() {
    if (!this.data.notifyCharUuid) {
      this.initializeBLEServices().then(success => {
        if (success && this.data.notifyCharUuid) {
          this._enableNotifications();
        } else {
          wx.showToast({
            title: '通知特性初始化失败',
            icon: 'none'
          });
        }
      });
      return;
    }
    this._enableNotifications();
  },

  _enableNotifications() {
    wx.notifyBLECharacteristicValueChange({
      deviceId: this.data.connectedDevice?.deviceId || '', 
      serviceId: this.data.notifyServiceUuid,
      characteristicId: this.data.notifyCharUuid,
      state: true,
      success: () => {
        wx.onBLECharacteristicValueChange((res) => {
          if (res.characteristicId === this.data.notifyCharUuid) {
            this.handleResponse(res.value);
          }
        });
      },
      fail: (err) => {
        console.error('使能通知特性失败:', err);
        wx.showToast({
          title: '使能通知特性失败: ' + err.errMsg,
          icon: 'none'
        });
      }
    });
  },

  // 连接设备后初始化
  // 设备连接成功后，初始化服务并启用通知
  onDeviceConnected() {
    this.setData({ status: '已连接' });
    this.stopScan();

    this.initializeBLEServices().then(success => {
      if (success) {
        this.enableNotifications();
      }
    });
  },
  
  // 清空接收数据
  clearData() {
    this.setData({
      deviceData: ''
    });
  },

  // 查找并写入特征值
  // 查找写入特征值并发送数据到蓝牙设备
  writeToCharacteristic(buffer: ArrayBuffer) {
    if (!this.data.connectedDevice) {
      console.error('未连接设备，无法发送指令');
      return;
    }

    if (this.data.writeCharUuid) {
      wx.writeBLECharacteristicValue({
        // 使用可选链操作符确保安全访问
        deviceId: this.data.connectedDevice?.deviceId || '', 
        serviceId: this.data.writeServiceUuid,
        characteristicId: this.data.writeCharUuid,
        value: buffer,
        success: () => {
          wx.showToast({
            title: '指令发送成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('写入特征值失败:', err);
          wx.showToast({
            title: `发送指令失败: ${err.errMsg}`,
            icon: 'none'
          });
        }
      });
      return;
    }

    setTimeout(() => {
      wx.getBLEDeviceServices({
        deviceId: this.data.connectedDevice?.deviceId || '', 
        success: (servicesRes) => {
          const writeService = servicesRes.services.find(s => {
            const shortUuid = getShortUuid(s.uuid);
            return shortUuid === 'FFE5' || s.uuid.toUpperCase().includes('FFE5');
          });

          if (!writeService) {
            console.error('未找到写入服务');
            wx.showToast({
              title: '未找到写入服务',
              icon: 'none'
            });
            return;
          }

          wx.getBLEDeviceCharacteristics({
            deviceId: this.data.connectedDevice?.deviceId || '', 
            serviceId: writeService.uuid,
            success: (res) => {
              const writeChar = res.characteristics.find(c => {
                const shortUuid = getShortUuid(c.uuid);
                return shortUuid === (this.data.writeCharUuid || 'FFE9') && c.properties.write;
              });

              if (!writeChar) {
                return;
              }

              this.setData({
                writeServiceUuid: writeService.uuid,
                writeCharUuid: writeChar.uuid
              });

              wx.writeBLECharacteristicValue({
                deviceId: this.data.connectedDevice?.deviceId || '', 
                serviceId: writeService.uuid,
                characteristicId: writeChar.uuid,
                value: buffer,
                success: () => {
                  wx.showToast({
                    title: '指令发送成功',
                    icon: 'success'
                  });
                },
                fail: (err) => {
                  if (err.errCode === 10008) {
                    wx.showToast({
                      title: '指令发送成功',
                      icon: 'success'
                    });
                  } else {
                    console.error('写入特征值失败:', err, '服务ID:', writeService.uuid, '特征值ID:', writeChar.uuid);
                    wx.showToast({
                      title: `发送指令失败: ${err.errMsg}`,
                      icon: 'none'
                    });
                  }
                }
              });
            },
            fail: (err) => {
              console.error('获取写入特征值失败:', err);
              wx.showToast({
                title: '获取写入特征值失败: ' + err.errMsg,
                icon: 'none'
              });
            }
          });
        },
        fail: (err) => {
          console.error('获取服务失败:', err);
          wx.showToast({
            title: '获取服务失败: ' + err.errMsg,
            icon: 'none'
          });
        }
      });
    }, 500);
  },

  // 处理蓝牙设备的响应
  // 处理蓝牙设备返回的数据，解析并显示
  // 修改：移除未使用的 cmdType 参数
  handleResponse(buffer: ArrayBuffer) {
    try {
      const hexData = Array.from(new Uint8Array(buffer))
        .map(b => b.toString(16).padStart(2, '0').toUpperCase())
        .join(' ');

      this.setData({
        deviceData: `[${new Date().toLocaleTimeString()}] Rx: ${hexData}\n` + (this.data.deviceData || '')
      });

      wx.showToast({
        title: '收到新数据',
        icon: 'none'
      });
    } catch (err) {
      console.error('响应解析失败:', err);
      this.setData({
        deviceData: `响应解析失败: ${(err as Error).message}`,
        servicesInfo: [],
        allServicesUuids: []
      });
    }
  },

  // 发送BLE指令
  sendBLECommand(settingsKey: string, defaultData: string) {
    if (!this.data.connectedDevice?.deviceId || !this.data.writeCharUuid) {
      wx.showToast({
        title: '设备未连接或特征值未初始化',
        icon: 'none'
      });
      return;
    }

    const settings = wx.getStorageSync(settingsKey) || { data: defaultData };
    const hexData = settings.data;
    
    const buffer = new Uint8Array((hexData.match(/[0-9a-fA-F]{2}/g) || []).map((byte: string) => parseInt(byte, 16))).buffer;
    wx.writeBLECharacteristicValue({
      deviceId: this.data.connectedDevice?.deviceId || '', 
      serviceId: this.data.writeServiceUuid,
      characteristicId: this.data.writeCharUuid,
      value: buffer,
      success: () => {
        wx.showToast({
          title: '指令发送成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        wx.showToast({
          title: `发送失败: ${err.errMsg}`,
          icon: 'none'
        });
      }
    });
  },

  // 通用按键指令发送
  sendButtonCommand(e: { currentTarget: { dataset: { buttonNumber: number } } }) {
    const buttonNumber = e.currentTarget.dataset.buttonNumber;
    this.sendBLECommand(`bleButton${buttonNumber}_Settings`, '01020304');
  },

  // 断开蓝牙连接
  disconnectDevice() {
    if (!this.data.connectedDevice?.deviceId) return;
    wx.closeBLEConnection({
      deviceId: this.data.connectedDevice?.deviceId || '', 
      success: () => {
        this.setData({
          connectedDevice: null,
          status: '',
          deviceData: ''
        });
        wx.showToast({ title: '已断开连接' });
      },
      fail: (err) => {
        console.error('断开连接失败:', err);
        wx.showToast({
          title: '断开连接失败: ' + err.errMsg,
          icon: 'none'
        });
        this.setData({
          status: ''
        });
      }
    });
  }
});

// 辅助函数，用于提取短 UUID
function getShortUuid(uuid?: string | null): string {
  if (!uuid) return '';
  const cleanUuid = uuid.replace(/-/g, '').toUpperCase();
  
  // 处理16位短UUID格式
  if (cleanUuid.length === 4) {
    return cleanUuid;
  }
  
  // 处理128位UUID转换为16位短UUID
  if (cleanUuid.length === 32) {
    return cleanUuid.slice(28, 32);
  }
  
  return uuid.replace(/-/g, '').toUpperCase().slice(-4);
}

function getFullUuid(shortUuid: string): string {
  if (shortUuid.length === 32) return shortUuid;
  if (shortUuid.length === 4) {
    return `0000${shortUuid}-0000-1000-8000-00805F9B34FB`;
  }
  return shortUuid;
}